import 'package:ac/common/style.dart';
import 'package:ac/model/ac_login_model.dart';
import 'package:ac/widget/ac_no_data_widget.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:get/get.dart';
import 'package:rongcloud_im_wrapper_plugin/rongcloud_im_wrapper_plugin.dart';

import 'ac_message_logic.dart';

class AcMessagePage extends StatelessWidget {
  final logic = Get.find<AcMessageLogic>();
  final state = Get.find<AcMessageLogic>().state;

  AcMessagePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: Column(
        children: [
          SizedBox(
            height: ScreenUtil().statusBarHeight,
          ),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 20.w),
            child: Container(
              height: 44.h,
              alignment: Alignment.centerLeft,
              child: Obx(() {
                var titleStyle = TextStyle(
                  fontSize: 20.sp,
                  color: textColorBlack,
                  fontWeight: FontWeight.bold,
                );
                var subTitleStyle = TextStyle(
                  fontSize: 15.sp,
                  color: textColorBlack.withOpacity(0.5),
                  fontWeight: FontWeight.w400,
                );
                return Row(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    GestureDetector(
                      onTap: () {
                        state.currentPage.value = 0;
                        state.pageController.jumpToPage(0);
                      },
                      child: Text(
                        "Messages",
                        style: state.currentPage.value == 0
                            ? titleStyle
                            : subTitleStyle,
                      ),
                    ),
                    SizedBox(width: 24.w),
                    GestureDetector(
                      onTap: () {
                        state.currentPage.value = 1;
                        state.pageController.jumpToPage(1);
                      },
                      child: Text(
                        "Followed",
                        style: state.currentPage.value == 1
                            ? titleStyle
                            : subTitleStyle,
                      ),
                    ),
                  ],
                );
              }),
            ),
          ),
          Expanded(
            child: PageView(
              controller: state.pageController,
              onPageChanged: (index) {
                state.currentPage.value = index;
                if (index == 1) {
                  logic.initFollowList();
                }
              },
              children: [
                Obx(() {
                  if (state.conversationList.isEmpty) {
                    return const AcNoDataWidget();
                  }
                  return ListView.builder(
                    padding: EdgeInsets.zero,
                    itemCount: state.conversationList.length,
                    itemBuilder: (context, index) {
                      var conversation = state.conversationList[index];
                      return Slidable(
                        key: const ValueKey(0),
                        endActionPane: ActionPane(
                          extentRatio: 0.2,
                          motion: const ScrollMotion(),
                          children: [
                            CustomSlidableAction(
                              backgroundColor: const Color(0xFFFF453A),
                              onPressed: (c) {
                                logic.deleteConversation(
                                  conversation.conversation!.conversationType!,
                                  conversation.conversation!.targetId!,
                                );
                              },
                              child: Image.asset(
                                "images/icon_delete2.png",
                                width: 24.w,
                              ),
                            ),
                          ],
                        ),
                        child: GestureDetector(
                          onTap: () {
                            logic.toChatPage(conversation);
                          },
                          behavior: HitTestBehavior.opaque,
                          child: Container(
                            height: 76.h,
                            padding: EdgeInsets.symmetric(horizontal: 20.w),
                            child: Row(
                              children: [
                                _avatar(conversation),
                                SizedBox(width: 10.w),
                                Expanded(
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Row(
                                        children: [
                                          Text(
                                            conversation.userinfo.nickname ??
                                                "",
                                            style: TextStyle(
                                              fontSize: 14.sp,
                                              color: textColorBlack,
                                            ),
                                          ),
                                          const Spacer(),
                                          Text(
                                            _timeStr(conversation.conversation!
                                                .lastMessage!.sentTime!),
                                            style: TextStyle(
                                              fontSize: 10.sp,
                                              color: textColorBlack
                                                  .withOpacity(0.3),
                                            ),
                                          )
                                        ],
                                      ),
                                      SizedBox(height: 10.h),
                                      Text(
                                        _getContentStr(
                                          conversation
                                              .conversation!.lastMessage,
                                        ),
                                        maxLines: 1,
                                        style: TextStyle(
                                          fontSize: 10.sp,
                                          color:
                                              textColorBlack.withOpacity(0.3),
                                          overflow: TextOverflow.ellipsis,
                                        ),
                                      )
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      );
                    },
                  );
                }),
                Obx(() {
                  if (state.followList.isEmpty) {
                    return const AcNoDataWidget();
                  }
                  return ListView.builder(
                    padding: EdgeInsets.zero,
                    itemBuilder: (c, i) {
                      Userinfo userinfo = state.followList[i];
                      return Container(
                        padding: EdgeInsets.symmetric(
                            horizontal: 18.w, vertical: 12.h),
                        child: Row(
                          children: [
                            ClipOval(
                              child: CachedNetworkImage(
                                imageUrl: userinfo.avatarUrl ?? "",
                                width: 44.w,
                              ),
                            ),
                            SizedBox(width: 10.w),
                            Expanded(
                              child: Text(
                                (userinfo.nickname ?? "").fixAutoLines(),
                                maxLines: 1,
                                style: TextStyle(
                                  fontSize: 14.sp,
                                  color: textColorBlack,
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ),
                            ),
                            SizedBox(width: 30.w),
                            GestureDetector(
                              onTap: () {
                                logic.unfollow(userinfo);
                              },
                              child: Container(
                                  padding: EdgeInsets.symmetric(
                                      horizontal: 8.w, vertical: 6.h),
                                  decoration: BoxDecoration(
                                    color: const Color(0xffcccccc),
                                    borderRadius: BorderRadius.circular(25.w),
                                  ),
                                  child: Text(
                                    "Unfollow",
                                    style: TextStyle(
                                      fontSize: 12.sp,
                                      color: Colors.white,
                                    ),
                                  )),
                            )
                          ],
                        ),
                      );
                    },
                    itemCount: state.followList.length,
                  );
                }),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Stack _avatar(ACConversation conversation) {
    return Stack(
      clipBehavior: Clip.none,
      children: [
        ClipOval(
          child: CachedNetworkImage(
            imageUrl: conversation.userinfo.avatarThumbUrl ?? "",
            width: 44.w,
            height: 44.w,
            fit: BoxFit.cover,
          ),
        ),
        Positioned(
          top: 0,
          right: 0,
          child: Visibility(
            visible: (conversation.conversation?.unreadCount ?? 0) > 0,
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 2.w),
              decoration: BoxDecoration(
                  border: Border.all(color: Colors.white, width: 1.w),
                  borderRadius: BorderRadius.circular(22.w),
                  color: Colors.red),
              child: Text(
                "${conversation.conversation?.unreadCount}",
                style: TextStyle(
                  fontSize: 10.sp,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        )
      ],
    );
  }

  String _getContentStr(RCIMIWMessage? lastMessage) {
    if (lastMessage == null) return "";
    switch (lastMessage.messageType!) {
      case RCIMIWMessageType.text:
        return (lastMessage as RCIMIWTextMessage).text ?? "";
      case RCIMIWMessageType.voice:
        return "[Voice]";
      case RCIMIWMessageType.image:
        return "[Image]";
      case RCIMIWMessageType.sight:
        return "[Video]";
      case RCIMIWMessageType.unknown:
      case RCIMIWMessageType.custom:
      case RCIMIWMessageType.file:
      case RCIMIWMessageType.gif:
      case RCIMIWMessageType.recall:
      case RCIMIWMessageType.reference:
      case RCIMIWMessageType.command:
      case RCIMIWMessageType.commandNotification:
      case RCIMIWMessageType.location:
      case RCIMIWMessageType.userCustom:
        break;
    }
    return "";
  }

  String _timeStr(int i) {
    var date = DateTime.fromMillisecondsSinceEpoch(i);
    var now = DateTime.now();
    if (date.year == now.year &&
        date.month == now.month &&
        date.day == now.day) {
      return "${date.hour.toString().padLeft(2, '0')}:${date.minute.toString().padLeft(2, '0')}";
    } else if (date.year == now.year) {
      return "${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}";
    } else {
      return "${date.year.toString()}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}";
    }
  }
}
